while
loop must be correct.If you change one of these three parts, the loop will do something different. Here is a section of a Java program that counts upwards by two's:
int count = 0; // count is initialized while ( count <= 6 ) // count is tested { System.out.println( "count is:" + count ); count = count + 2; // count is increased by 2 } System.out.println( "Done counting by two's." );
Here is what the program prints:
count is: 0 count is: 2 count is: 4 count is: 6 Done counting by two's.
Here is what happens, step-by-tedious-step:
count
is initialized to 0.count <= 6
is evaluated, yielding TRUE.count
.count
is now 2.count <= 6
is evaluated, yielding TRUEcount
.count
is now 4.count <= 6
is evaluated, yielding TRUE.count
.count
is now 6.count <= 6
is evaluated, yielding TRUE.count
is now 8.count <= 6
is evaluated, yielding FALSE.